from flask import Flask, render_template, request,send_from_directory
import query
from flask import Blueprint
from MySQL import mysql_c
import os
from shutil import copyfile
import datetime
import zipfile
from flask_cors import CORS
from Log import log,error,notice

job_api = Blueprint('job_api', __name__)
UPLOAD_FOLDER = 'upload/'
TEMPLATE_FOLDER = 'temp/'
CORS(job_api)	# 注册CORS

#作业提交
@job_api.route('/uploader', methods = ['get', 'post'])
def uploader():
   t = request.files.to_dict()
   print(request.form)
   if t:
        f = request.files['file']
   else: f = None
   username = request.form.get('username')
   title = request.form.get('title')
   note = request.form.get('note')
   classesid = request.form.get('classid')
   num = request.form.get('number')

   if username and title and note and classesid and num:
      datetimes = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
      if f:
        f.save(os.path.join(UPLOAD_FOLDER,username + "_" +datetimes+".png"))
        url = os.path.join(UPLOAD_FOLDER,username + "_" +datetimes+".png")
      else:url=""
      backinf = query.job_information_up(mysql_c, username,title,note,int(classesid),datetimes,url,num)
      if backinf[0] == -1:
         return {"msg": "提交作业失败", "state": -1, "data": None}
      elif backinf[0] == 1:
         return {"msg": "提交作业成功", "state": 1, "data": backinf[1]}
   else:
      return {"msg": "提交作业失败，发生毁灭性错误", "state":-1, "data": None}

#作业检索
@job_api.route('/job_search', methods=['get', 'post'])
def jobs():
    if (request.method == 'POST'):
        username = request.json.get('username')
        classid = request.json.get('classid')
        teacherid = request.json.get('teacherid')
        order = request.json.get('order')
        page = request.json.get('page')
        number = request.json.get("number")
        page_size = request.json.get('pagesize')
    else:
        username = request.values.get('username')
        classid = request.values.get('classid')
        teacherid = request.values.get('teacherid')
        order = request.values.get('order')
        number = request.values.get("number")
        page = request.values.get('page')
        page_size = request.values.get('pagesize')

        if not username:
            username = "all"
        if not classid:
            classid = -1
        if not order:
            order = 0
        if not page:
            page = -1
        if not page_size:
            page_size = 10
        if not number:
            number = -1
        if not teacherid:
            teacherid=-1
        backinf = query.get_job(mysql_c,username,int(classid),int(order),page,int(page_size),number,teacherid)
        if backinf[0] == -1:
                return {"msg": "获取失败", "state": -1, "data": None}
        elif backinf[0] == 1:
                return {"msg": "获取成功", "state": 1, "data":backinf[1]}

#作业下载
@job_api.route('/job_download', methods=['get', 'post'])
def jd():
    if (request.method == 'POST'):
        jid = request.json.get('jobid')
    else:
        jid = request.values.get('jobid')

        if jid:
            if not os.path.exists(os.path.join(TEMPLATE_FOLDER,str(jid)+"_job_all")):
                os.mkdir(os.path.join(TEMPLATE_FOLDER,str(jid)+"_job_all"))
            if os.path.exists(os.path.join(TEMPLATE_FOLDER, str(jid)+"_job_all"+".zip")):
                os.remove(os.path.join(TEMPLATE_FOLDER, str(jid)+"_job_all"+".zip"))
            backinf = query.search_job(mysql_c,jid)
            if backinf[0] == 1:
                backinf = backinf[1]
                text_file = open(TEMPLATE_FOLDER+str(jid)+"_job_all/text.txt", "w")
                text_file.write(backinf['title']+"\n"+backinf['note'])
                text_file.close()

                if backinf['url'] is not "":
                    copyfile(backinf['url'], os.path.join(TEMPLATE_FOLDER,str(jid)+"_job_all/picture.png"))

                startdir = TEMPLATE_FOLDER+str(jid)+"_job_all"
                file_news = startdir + '.zip'  # 压缩后文件夹的名字
                z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)  # 参数一：文件夹名
                for dirpath, dirnames, filenames in os.walk(startdir):
                    fpath = dirpath.replace(startdir, '')
                    fpath = fpath and fpath + os.sep or ''
                    for filename in filenames:
                        z.write(os.path.join(dirpath, filename), fpath + filename)
                        log('压缩成功')
                z.close()

                return send_from_directory(TEMPLATE_FOLDER,filename=str(jid)+"_job_all"+".zip",as_attachment=True)

            elif backinf[0] == -1:
                return {"msg": "获取失败", "state": -1, "data": None}
        else:
            return {"msg": "数据不完整", "state": -1, "data": None}

#作业删除
@job_api.route('/job_delete', methods=['get', 'post'])
def jobde():
    if (request.method == 'POST'):
        jid = request.json.get('jobid')
    else:
        jid = request.values.get('jobid')

    if jid:
        backinf = query.delete_job(mysql_c, jid)
        if backinf[0] == 1:
            return {"msg": "删除成功", "state": 1}
        else:
            return {"msg": "删除失败", "state": -1}
    else:
        return {"msg": "数据不完整", "state": -1}

#作业更新
@job_api.route('/job_up', methods = ['get', 'post'])
def jup():
   t = request.files.to_dict()
   if t:
    f = request.files['file']
   else:f=None
   fbool = False
   title = request.form.get('title')
   note = request.form.get('note')
   jid = request.form.get('jobid')
   comment = request.form.get('comment')

   if jid:
      datetimes = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
      if f:
           fbool = True
           f.save(os.path.join(UPLOAD_FOLDER, jid + "_jobid_" + datetimes + ".png"))
           url = os.path.join(UPLOAD_FOLDER, jid + "_jobid_" + datetimes + ".png")
      else:url=""
      if not title:
          title = -1
      if not note:
          note = -1
      if not comment:
          comment = -1

      backinf = query.job_update(mysql_c, title,note,jid,url,fbool,comment)
      if backinf[0] == -1:
         return {"msg": "更新作业失败", "state": -1, "data": None}
      elif backinf[0] == 1:
         return {"msg": "更新作业成功", "state": 1, "data": backinf[1]}
   else:
      return {"msg": "更新作业失败，发生毁灭性错误", "state": -1, "data": None}

#作业重复性检查，检查某轮作业是否重复出现
@job_api.route('/job_exist_check', methods = ['get', 'post'])
def jcheck():
    if (request.method == 'POST'):
        username = request.json.get('username')
        cid = request.json.get('classid')
        jid = request.json.get('jobid')
    else:
        username = request.values.get('username')
        cid = request.values.get('classid')
        jid = request.values.get('jobid')

    if jid and cid and username:
        backinf = query.job_repeat_check(mysql_c, username,cid,jid)
        if backinf[0] == 1:
            return {"msg": "这一轮次的作业从未出现", "state": 1,"data" : False}
        else:
            return {"msg": "这一轮次的作业已经出现", "state": 1,"data" : True}
    else:
        return {"msg": "数据不完整", "state": -1,"data":None}